package com.slx.sthq.common.utils.ssh;

import cn.hutool.extra.ssh.JschUtil;
import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JSchUtil {

    public static final String HOST = "169.254.247.99";
    public static final Integer PORT = 22;
    public static final String USER = "root";
    public static final String PASSWORD = "Admin123@pl";


    public static String command(String command) throws Exception {
        Session session = JschUtil.createSession(HOST, PORT, USER, PASSWORD);
        session.connect();


        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setCommand(command);
        channelExec.setInputStream(null);
        channelExec.setPty(true);

        // 获取命令执行的输出
        InputStream in = channelExec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        channelExec.connect();
        StringBuffer result = new StringBuffer();
        // 读取输出
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            // 在这里可以对输出进行处理
            result.append(line);
        }
        channelExec.disconnect();
        session.disconnect();
        JschUtil.closeAll();
        return result.toString();
    }


    public static void downloadFile(String remoteFilePath, String localFilePath) throws Exception {

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(USER, HOST, PORT);
            session.setPassword("root123456");
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get(remoteFilePath, localFilePath);

            sftpChannel.disconnect();
            session.disconnect();

            System.out.println("文件下载成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

